import { App, Button, Card, Col, Form, Input, message, Row, Table } from 'antd';
import '../user/index.scss';
import { queryUser,deleteUser } from '@/apis/user'
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import type { User, UserDto, UserPropsType } from '@/types';
import { DeleteOutlined, FormOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import UserAddForm from '@/components/UserForm';
import { useForm } from 'antd/es/form/Form';

const User = forwardRef((props: UserPropsType, ref) => {
    const { modal } = App.useApp();
    /** 
     * 更改查询条件回调 
     * 调用时机
     * 1.修改当前页数和每页显示条数时
     * 2.查询条件表单的条件修改
     */
    const changeSeleteCondition = (params: UserDto) => {
        console.log("changeSeleteCondition========>",params);
        setQueryForm(params);   
    }

    /** 查询  */
    const getUserData = async () => {
        setLoading(true);
        const res = await queryUser(queryForm);
        console.log("用户数据=======>",res.data.records);
        // 获取数据为空 且 当前页数不为1时，将当前页数-1再查一遍
        /**
         * 解决：
         *  1.在删除第二页最后一条数据后，重新查询时当前页数还是2，解决后：查不到之后，会-1变成1
         *  2.当前在第二页，然后搜索存在的数据的条件，若存在的数据不满足2页，则会显示为空 解决后：查不到之后，会-1变成1
         */
        if (res.data.records.length === 0 && queryForm.current !== 1) {
            setQueryForm({
                ...queryForm,
                current: queryForm.current - 1
            })
            return;
        }
        setTableData(res.data.records);
        setTotal(res.data.total);
        setLoading(false);
    }

    /** 新增 */
    const addUserData = async () => {
        userFormRef.current.open();
    }

    /** 编辑  */
    const editUserData = async (record: User) => {
        userFormRef.current.open(record);
    }

    /** 删除 */
    const removeUser = async (id: string) => {
        const deleteIds: string[] = [];
        deleteIds.push(id);
        modal.confirm({
            title: '温馨提示',
            content: '是否删除选中的数据？',
            okText: '确认',
            cancelText: '取消',
            async onOk(){
               const res = await deleteUser(deleteIds);
                if (res.code === 200) {
                    message.success("删除成功！");
                    await getUserData();
                }else {
                    message.success(res.msg);
                } 
            },
            onCancel: () => {

            }
        })
    }

    /** 重置  */
    const reset = () => {
        form.resetFields();
        setQueryForm({
            current: 1,
            size: 6
        })
        setSelectDataIds([]);
        setSelectDatas([]);
        // todo 清空表格选中的数据项
    }

    /** 暴露给外部组件获取选中的数据回调  */
    const handleReturn = async () => {
        if (selectedDatas.length === 0) {
            message.warning('请选择数据后再进行操作！');
            return [];
        }
        return selectedDatas;
    }   

    /** 批量删除  */
    const removeUserBatch = async () => {
        if (selectDataIds.length === 0) {
            message.warning('请先选择数据再进行操作！')
            return;
        }
        modal.confirm({
            title: '温馨提示',
            content: '是否删除选中的数据？',
            okText: '确认',
            cancelText: '取消',
            async onOk(){
               const res = await deleteUser(selectDataIds);
                if (res.code === 200) {
                    message.success("删除成功！");
                    await getUserData();
                }else {
                    message.success(res.msg);
                } 
            },
            onCancel: () => {

            }
        })
    }

    /** 表格选中回调  */
    const tabSelectChange = (selectedRowKeys: React.Key[], selectedRows: User[]) => {
        setSelectDataIds(selectedRowKeys as string[]);
        setSelectDatas(selectedRows as User[]);
        // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    }
    // 表单标识
    const [form] = Form.useForm();
    // 表格数据
    const [tableData,setTableData]  = useState<User[]>([]);
    // 总记录数
    const [total,setTotal] = useState(0);
    // 查询条件
    const [queryForm,setQueryForm] = useState<UserDto>({
        current: 1,
        size: 6
    })
    // 加载中标识
    const [loading, setLoading] = useState(false);
    // 弹框组件标识
    const userFormRef = useRef(null);
    // 当前选中的数据行id
    const [selectDataIds,setSelectDataIds] = useState<string[]>([]);
    // 当前选中的数据
    const [selectedDatas,setSelectDatas] = useState<User[]>([]);    

    useEffect(() => {
        getUserData();
    }, [queryForm]); // 当 queryForm 的值变化时才触发

    useEffect(() => {
        if (props.selectUserDatas) {
            const selectDatas: User[] = JSON.parse(JSON.stringify(props.selectUserDatas));
            const selectDataIds = selectDatas.map(Item => Item.id) as string[];
            setSelectDataIds(selectDataIds);
            setSelectDatas(selectDatas);   
        }
    },[props.selectUserDatas]);

    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '年龄',
            dataIndex: 'age',
        },
        {
            title: '联系号码',
            dataIndex: 'contactNumber',
        },
        {
            title: '操作',
            dataIndex: 'action',
            render: (value: string, record:User) => (
                <>
                    <Row gutter={16}>
                        <Col>
                            <Button onClick={() => editUserData(record)} color='primary' variant="outlined" icon={<FormOutlined />}/>
                        </Col>
                        <Col>
                           <Button onClick={() => removeUser(record.id!)} color="danger" variant="outlined" icon={<DeleteOutlined />}/>
                        </Col>
                    </Row>
                </>
            ),
        }
    ];

    useImperativeHandle(ref, () => ({
        handleReturn: handleReturn,
        reset: reset
    }));

    return (
        <div className='user-container'>
            <Card title='查询条件' style={{ borderRadius: 0 }}>
                <Form
                    form={form}
                    layout="inline"
                    name="user"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ width: '100%' }}
                    initialValues={{ remember: true }}
                    onFinish={(val) => { changeSeleteCondition({...queryForm,...val,current: 1}) }}
                    autoComplete="off"
                >
                    <Row style={{ width: '100%' }}>
                        <Form.Item<User>
                            label="姓名"
                            name="name"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item<User>
                            label="联系号码"
                            name="contactNumber"
                        >
                            <Input />
                        </Form.Item>
                    </Row>

                    <Row justify="end" style={{ width: '100%',marginTop: '20px' }}>
                        {
                            props?.isOutOpen || (
                                <Form.Item label={null}>
                                    <Button type="primary" onClick={() => addUserData()} htmlType="button" icon={<PlusOutlined />}>
                                        新增
                                    </Button>
                                </Form.Item>
                            )
                        }
                        {
                            props?.isOutOpen || (
                                <Form.Item label={null}>
                                    <Button variant='solid' color='danger' onClick={() => removeUserBatch()} htmlType="button" icon={<DeleteOutlined />}>
                                        删除
                                    </Button>
                                </Form.Item>
                            )
                        }
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                查询
                            </Button>
                        </Form.Item>
                    </Row>
                </Form>
            </Card>

            <Card title='查询结果' style={{ marginTop: '20px',borderRadius: 0 }}>
                <Table
                    rowKey="id" 
                    loading={loading}
                    pagination={{ 
                        position: ['bottomRight'],
                        current: queryForm.current,
                        pageSize: queryForm.size,
                        total: total,
                        onChange: (current, size) => changeSeleteCondition({...form.getFieldsValue(),current,size}),
                        showTotal: (total) => `共 ${total} 条数据`,
                        showSizeChanger: true,
                        pageSizeOptions: [6,10,20,50,100]
                    }}
                    rowSelection={{ type: 'checkbox',onChange: tabSelectChange,selectedRowKeys: selectDataIds,preserveSelectedRowKeys: true }} 
                    dataSource={tableData} 
                    columns={columns} 
                />
            </Card>
            <UserAddForm ref={userFormRef} reQuery={() => getUserData()}></UserAddForm>
        </div>
    )
})

export default User;